package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.tools.REXTools;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.views.ValidationCode;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class MineMsgPhoneActivity extends BaseActivity implements View.OnClickListener{

    private ImageView homeback;
    private LinearLayout homesearch;
    private Button msgphonesurebt;
    private String phone;
    private TextView oldphone;
    private EditText inimgcode;
    private ValidationCode getimgcode;
    private EditText incode;
    private Button getcode;
    private String tImgCode;
    private String tInCode;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String messageId;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fw_home);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        phone = getIntent().getStringExtra("phone");
        initHomeView();
        if (phone!=null){
            oldphone.setText(REXTools.hidePhone(phone));
        }
    }


    private void initHomeView() {
        homeback = (ImageView) findViewById(R.id.msgphone_back);
        msgphonesurebt = (Button) findViewById(R.id.msgphone_surebt);
        oldphone = (TextView) findViewById(R.id.phone_oldphone);
        inimgcode = (EditText) findViewById(R.id.msgphone_inimgcode);
        getimgcode = (ValidationCode) findViewById(R.id.msgphone_imgcode);
        incode = (EditText) findViewById(R.id.msgphone_incode);
        getcode = (Button) findViewById(R.id.msgphone_getcode);
        backmain = (ImageView) findViewById(R.id.msgphone_backmain);
        //设置点击事件
        backmain.setOnClickListener(this);
        homeback.setOnClickListener(this);
        msgphonesurebt.setOnClickListener(this);
        getcode.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        getInPutData();
        switch (v.getId()){
            case R.id.msgphone_backmain:
                startActivity(new Intent(MineMsgPhoneActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.msgphone_getcode:
                if (!tImgCode.equals("")){
                    if (tImgCode.equals(getimgcode.getCodeString())){
                        MyTimer timer = new MyTimer(120000,1000);
                        timer.start();
                        getCode();
                    }else {
                        Toast.makeText(this, "图形验证码错误，请注意大小写", Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.msgphone_back:
                finish();
                break;
            case R.id.msgphone_surebt:

                if (!tImgCode.equals("")){
                    if (tImgCode.equals(getimgcode.getCodeString())){
                        if (!tInCode.equals("")){

                            revisePhone();


                        }else {
                            Toast.makeText(this, "请输入手机验证码", Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        Toast.makeText(this, "图形验证码错误，请注意大小写", Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Toast.makeText(this, "请输入图形验证码", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void revisePhone() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.CORRECTPHONE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("messageId",messageId);
        jsonObject.put("code",tInCode);
        params.addParameter("params",jsonObject.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 验证原手机号-"+result);
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Intent intent =new Intent(MineMsgPhoneActivity.this,MsgNewPhoneActivity.class);
                    intent.putExtra("mid",messageId);
                    startActivity(intent);
                }else {}
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 验证原手机号--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getInPutData() {
        tImgCode = String.valueOf(inimgcode.getText());
        tInCode = String.valueOf(incode.getText());
    }

    class MyTimer extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                  倒计时数        to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *           倒计时间隔               {@link #onTick(long)} callbacks.
         */
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            getcode.setClickable(false);
            getcode.setText(millisUntilFinished/1000+" s 后发送");
        }

        @Override
        public void onFinish() {
            getcode.setClickable(true);
            getcode.setText("验证码");
        }
    }

    // 获取验证码
    public void getCode() {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/verify/sendCode");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","6");
        params.addParameter("params",jsonObject.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 验证码-"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取messageid
                String status = obj.getString("status");
                if (status.equals("1")){
                    String data = obj.getString("data");
                    JSONObject object = JSON.parseObject(data);
                    messageId = object.getString("messageId");

                }else {}


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 演这个吗--"+ex);
                ErrType.errType(MineMsgPhoneActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
